package village.rainbow.dailyscene.uicontrol;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.Path;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Environment;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;

public class DrawView extends View {
	private static final float TOUCH_TOLERANCE = 4;
	public Canvas mCanvas;
	
	public boolean hasSigned = false;
	
	float mX, mY;
	Bitmap mBitmap;
	Path mPath;
	Paint mBitmapPaint;
	Paint mPaint;

	public DrawView(Context c) {
		super(c);
		init();
	}

	public DrawView(Context context, AttributeSet attrs) {
		super(context, attrs);
		init();
	}

	private void init() {
		mPaint = new Paint();
		mPaint.setAntiAlias(true);
		mPaint.setDither(true);
		mPaint.setColor(0xFF000000);
		mPaint.setStyle(Paint.Style.STROKE);
		mPaint.setStrokeJoin(Paint.Join.ROUND);
		mPaint.setStrokeCap(Paint.Cap.ROUND);
		mPaint.setStrokeWidth(10);
		mPath = new Path();
		mBitmapPaint = new Paint(Paint.DITHER_FLAG);
	}
	
	public void setImageBitmap(Bitmap bitmap){
		mBitmap = bitmap;
	}
	
	public void setImageDrawable(Drawable drawable){
		mBitmap = drawableToBitmap(drawable);
	}
	
	private Bitmap drawableToBitmap (Drawable drawable) {
	    if (drawable instanceof BitmapDrawable) {
	        return ((BitmapDrawable)drawable).getBitmap();
	    }

	    Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), Config.ARGB_8888);
	    Canvas canvas = new Canvas(bitmap); 
	    drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
	    drawable.draw(canvas);

	    return bitmap;
	}

	@Override
	protected void onSizeChanged(int w, int h, int oldw, int oldh) {
		super.onSizeChanged(w, h, oldw, oldh);

		if (mBitmap != null) {
			mBitmap.recycle();
		}
		
		if(w > h) {
			if (w < h * 2)
				h = w / 2;
			else
				w = h * 2;
		}
		else {
			if (h < w * 2)
				w = h / 2;
			else
				h = w * 2;
		}
		
		mBitmap = Bitmap.createBitmap(w, h, Bitmap.Config.ARGB_8888);
		mBitmap.eraseColor(Color.WHITE);
		Canvas canvas = new Canvas(mBitmap);
		this.mCanvas = canvas;
	}

	@Override
	protected void onDraw(Canvas canvas) {
		canvas.drawColor(0xFFFFFFFF);
		canvas.drawBitmap(mBitmap, 0, 0, mBitmapPaint);
		canvas.drawPath(mPath, mPaint);
	}
	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		float x = event.getX();
		float y = event.getY();
		
		switch (event.getAction()) {
		case MotionEvent.ACTION_DOWN:
			hasSigned = true;
			touch_start(x, y);
			invalidate();
			break;
		case MotionEvent.ACTION_MOVE:
			hasSigned = true;
			touch_move(x, y);
			invalidate();
			break;
		case MotionEvent.ACTION_UP:
			hasSigned = true;
			touch_up();
			invalidate();
			break;
		}
		return true;
	}
	
	public byte[] getDataFormatPNG() throws IOException{
		float f;
		if(mBitmap.getWidth() > mBitmap.getHeight())
			f = 128f / mBitmap.getWidth();
		else
			f = 128f / mBitmap.getHeight();
		
		Matrix mtx = new Matrix();
		mtx.reset();
		mtx.setRotate(-180);
		mtx.setScale(f, -f);
		
		Bitmap bitmap = Bitmap.createBitmap(mBitmap, 0, 0, mBitmap.getWidth(),
				mBitmap.getHeight(), mtx, true);
		
		String dirPath = Environment.getExternalStorageDirectory() + "/tempFilePath/";
		File dir = new File(dirPath);
		if(!dir.exists())
			dir.mkdir();
		
		File imageTempFile = File.createTempFile("tempfile", null, dir);
		FileOutputStream fous = new FileOutputStream(imageTempFile);
		
		bitmap.compress(CompressFormat.PNG, 90, fous);
		fous.flush();
		fous.close();
		
		FileInputStream fis = new FileInputStream(imageTempFile);
		byte[] imagebyte = new byte[(int)imageTempFile.length()];
		fis.read(imagebyte);
		fis.close();
		
		return imagebyte;
	}
	
	private void touch_start(float x, float y) {
		mPath.reset();
		mPath.moveTo(x, y);
		mX = x;
		mY = y;
	}

	private void touch_move(float x, float y) {
		float dx = Math.abs(x - mX);
		float dy = Math.abs(y - mY);
		if (dx >= TOUCH_TOLERANCE || dy >= TOUCH_TOLERANCE) {
			mPath.quadTo(mX, mY, (x + mX) / 2, (y + mY) / 2);
			mX = x;
			mY = y;
		}
	}

	private void touch_up() {
		mPath.lineTo(mX, mY);
		// commit the path to our offscreen
		if (mCanvas != null)
			mCanvas.drawPath(mPath, mPaint);

		// kill this so we don't double draw
		mPath.reset();
	}
	
	public void clear(){
		mBitmap.eraseColor(Color.WHITE);
		invalidate();
	}

}
